<template>
  <!-- 修改 负责人信息  --   以前新增企业只有三步走，给之前的企业用的 -->
  <view class="placeSafetyxdirectorOld">
    <view class="wrapper">
      <view class="wrapper-item content">
        <u-form :model="form" ref="form" label-width="100" :error-type="errorType">
          <view class="title-name">身份信息</view>
          <u-form-item label="证件照片" borderBottom :required="true">
          </u-form-item>
          <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="1"
            width="310" height="180">
            <image :src="baseImgUrl + 'card_3.png'" style="width: 640rpx; height: 360rpx"></image>
          </u-upload>

          <u-form-item label="姓名" borderBottom :required="true">
            <u--input v-model="form.dutyPersonName" border="none" placeholder="请填写" :maxlength="30"></u--input>
          </u-form-item>

          <u-form-item label="身份证号" borderBottom :required="true">
            <u--input type="idcard" v-model="form.idCard" border="none" placeholder="请填写" :maxlength="18"
              @blur="idCardHandle"></u--input>
          </u-form-item>

          <!--  <u-form-item label="户籍地址" borderBottom :required="true">
            <u--input v-model="form.residenceDetail" border="none" placeholder="请填写" :maxlength="30"></u--input>
          </u-form-item> -->

          <u-form-item label="手机号码" borderBottom :required="true">
            <u--input v-model="form.mobile" border="none" placeholder="请填写" type="number" :maxlength="11"
              @blur="phoneHandle"></u--input>
          </u-form-item>
        </u-form>
      </view>
    </view>

    <view class="btns thispageBtn">
      <button class="cancel-btn lt" type="primary" @click="navBack('back', 1, 1)">
        取消
      </button>
      <button class="submit-btn" type="primary" @click="submitHandle">
        保存
      </button>
    </view>

    <canvas canvas-id="myCanvas" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
      style="position: fixed; top: -9999999999999rpx" @error="error"></canvas>
    <yy-watermark></yy-watermark>
  </view>
</template>

<script>
  import {
    updateCompany
  } from "@/api/myself.js";
  import {
    Toast,
    navBack,
    uniTrim,
    checkIDCard,
    getBase64Two,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";

  export default {
    name: "placeSafetyxdirectorOld",
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        imgPrefix: uni.getStorageSync("imgPrefix"),
        options: {},
        form: {},
        errorType: ["none"],
        fileList: [],
        fileList2: [],
        canvasWidth: 0,
        canvasHeight: 0,
      };
    },
    onLoad(options) {
      this.options = options;
    },
    methods: {
      navBack,
      idCardHandle() {
        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag) {
          Toast("请输入正确的证件号码");
          return;
        }
      },
      phoneHandle() {
        if (this.form.mobile && !this.$u.test.mobile(this.form.mobile)) {
          Toast("请输入正确的手机号");
          return;
        }
      },
      afterRead(info) {
        let _this = this;

        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Handle(res.data.access_token, info);
          },
        });
      },
      base64Handle(token, info) {
        let _this = this;

        getBase64Two(info.file.url)
          .then((res) => {
            return res;
          })
          .then((res) => {
            uni.request({
              url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`,
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              data: {
                id_card_side: "front",
                image: res,
                detect_direction: true,
              },
              // success(resbai) {
              //   let { statusCode, data } = resbai;
              //   if (statusCode == 200 && data.words_result["公民身份号码"]) {
              //     _this.$set(
              //       _this.form,
              //       "dutyPersonName",
              //       data.words_result.姓名.words
              //     );
              //     _this.$set(
              //       _this.form,
              //       "idCard",
              //       data.words_result.公民身份号码.words
              //     );
              //     _this.$set(
              //       _this.form,
              //       "residenceDetail",
              //       data.words_result.住址.words
              //     );
              //     _this.uploadImage(info.file.url, 20);
              //     return;
              //   }

              //   Toast("未识别");
              //   _this.uploadImage(info.file.url, 20);
              //   // Toast("请上传正确的身份证证件照片");
              // },
              success(resbai) {
                let {
                  statusCode,
                  data
                } = resbai;

                if (statusCode == 200 && data.words_result["姓名"]) {
                  _this.$set(
                    _this.form,
                    "dutyPersonName",
                    data.words_result.姓名.words
                  );
                  _this.$set(
                    _this.form,
                    "idCard",
                    data.words_result.公民身份号码.words
                  );
                  // _this.$set(
                  //   _this.form,
                  //   "residenceDetail",
                  //   data.words_result.住址.words
                  // );
                  console.log(data, "datadata");
                  // 图片旋转  start
                  var yingNum = 0;
                  var direction = data.direction;
                  if (direction != -1 && direction != 0) {
                    if (direction == 1) {
                      //逆时针90°
                      yingNum = 90;
                    } else if (direction == 2) {
                      //逆时针180°
                      yingNum = 180;
                    } else if (direction == 3) {
                      //逆时针270°
                      yingNum = 270;
                    }
                  }

                  if (yingNum) {
                    uni.showLoading({
                      title: "图片加载中",
                    });
                    _this.drapImgLast(info, yingNum);
                    return;
                  }
                  // 图片旋转  end

                  _this.uploadImage(info.file.url, 20);
                  return;
                }

                Toast("未识别");
                _this.uploadImage(info.file.url, 20);
                // Toast("请上传正确的营业执照");
              },
            });
          });
      },
      drapImgLast(info, yingNum) {
        let _this = this;
        const ctx = uni.createCanvasContext("myCanvas", _this);

        uni.getImageInfo({
          src: info.file.url,
          success(res1) {
            let {
              width,
              height,
              path
            } = res1;
            if (yingNum == 90) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, width, width); // 清空画布

              ctx.translate(_this.canvasWidth, 0);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 270) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, height, width); // 清空画布

              ctx.translate(0, _this.canvasHeight - 10);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 180) {
              _this.canvasWidth = width;
              _this.canvasHeight = height;
              ctx.clearRect(0, 0, width, height); // 清空画布

              ctx.translate(_this.canvasWidth, _this.canvasHeight);
              ctx.rotate((-yingNum * Math.PI) / 180);
            }
            ctx.drawImage(path, 0, 0);

            // 将生成的canvas图片，转为真实图片
            ctx.draw(false, () => {
              setTimeout(() => {
                uni.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: "myCanvas",
                  success(res2) {
                    console.log(res2, "RRRRRRRRR");
                    _this.uploadImage(res2.tempFilePath, 20);
                  },
                });
              }, 50);
            });
          },
        });
      },
      uploadImage(fileurl, type) {
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type: type,
            },
          })
          .then((res) => {
            let {
              fullPath,
              halfPath
            } = res.result;
            if (type == 20) {
              _this.fileList.push({
                url: fullPath
              });
              _this.form.personImage = halfPath;
            }
          })
          .finally(() => {})
      },
      deletePic() {
        this.fileList = [];
        this.form.personImage = "";
      },
      submitHandle() {
        let {
          personImage,
          dutyPersonName,
          idCard,
          // residenceDetail,
          mobile
        } =
        this.form;
        if (!this.fileList.length) {
          Toast("请上传证件照片");
          return;
        }

        if (!dutyPersonName || !uniTrim(dutyPersonName)) {
          Toast("请输入姓名");
          return;
        }

        let legalPersonRegexp =
          /^[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]*$/;
        if (!legalPersonRegexp.test(dutyPersonName)) {
          Toast("姓名只能输入汉字");
          return;
        }

        if (!idCard || !uniTrim(idCard)) {
          Toast("请输入身份证号");
          return;
        }

        let idCardFlag = checkIDCard(this.form.idCard);
        if (!idCardFlag) {
          Toast("请输入正确的证件号码");
          return;
        }

        // if (!residenceDetail || !uniTrim(residenceDetail)) {
        //   Toast("请输入户籍地址");
        //   return;
        // }

        let data = {
          companyDutyPersonInfo: {
            id: this.options.id,
            mobile: mobile,
            dutyPersonName: dutyPersonName,
            idCard: idCard,
            personImage: personImage,
            // residenceDetail: residenceDetail,
          },
        };

        updateCompany(data).then((res) => {
          if (res.code == 200) {
            Toast("保存成功");
            navBack("back");
            return;
          }
          Toast(res.message);
        });
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .placeSafetyxdirectorOld {
    flex: 1;
    background-color: #f3f3f3;

    .placeSafetyxdirectorOld-title {
      position: absolute;
      top: 10rpx;
      left: 6%;
      color: #ffffff;
      font-size: 34rpx;
      font-weight: bold;
    }

    .wrapper {
      position: absolute;
      top: 30rpx;
      left: 50%;
      transform: translateX(-50%);

      .wrapper-item {
        margin-bottom: 2vh;
        padding: 35rpx 30rpx;
        background-color: #ffffff;
        border-radius: 10rpx;
        width: 702rpx;
      }

      .content {
        margin: 0 auto;
        height: calc(100vh - 90px);
        overflow-y: auto;
      }
    }

    .title-name {
      font-size: 30rpx;
      font-weight: bold;
    }

    .thispageBtn {
      position: absolute;
      width: 100vw;
      bottom: 0;
    }
  }
</style>